package de.lizenzverwaltung.model.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.sql.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import de.lizenzverwaltung.model.dao.NachrichtDAO;
import de.lizenzverwaltung.model.dao.UserDAO;
import de.lizenzverwaltung.model.dao.UserDAOFactory;
import de.lizenzverwaltung.model.entities.Nachricht;
import de.lizenzverwaltung.model.entities.User;

public class NachrichtDAOImpl extends DAOBase implements NachrichtDAO {

	private Log logger = LogFactory.getLog(NachrichtDAOImpl.class);
	private UserDAO dao = UserDAOFactory.getInstance();
	
	/**
	* {@inheritDoc}
	*/
	@Override
	public List<Nachricht> getAllNachrichten() {
		logger.debug("entering getAllNachrichten");
		List<Nachricht> nachrichtenListe = new ArrayList<Nachricht>();
		
		//
		String query = "SELECT * FROM nachricht";
		try {
			Connection conn = openConnection();
			PreparedStatement pstmt = conn.prepareStatement(query);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()){
				logger.debug("entering getAllNachrichten - ResultSet");
				//User ermitteln
				User user = this.dao.getUser(rs.getString("userid"));
				nachrichtenListe.add(new Nachricht(rs.getString("nachrichtID"),rs.getString("nachrichtText"),user,rs.getDate("datum")));		
			}
			pstmt.close();
			conn.close();
		} catch (SQLException e) {
			logger.error("SQLException occured (Query=" + query + ")", e);
		}
		return nachrichtenListe;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean loescheNachricht(String id) {
		logger.debug("entering loescheNachricht");
		boolean result = false ;
		
		String query = "DELETE FROM nachricht where nachrichtid='"+id+"'";
		try {
			Connection conn = openConnection() ;
			PreparedStatement pstmt = conn.prepareStatement(query) ;
			pstmt.execute() ;
			pstmt.close();
			conn.close(); 
			result = true ;
		} catch (SQLException sqle) {
			logger.error("SQLException occured (Query=" + query + ")", sqle) ;
			result = false ;
		}
		return result;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean speicherNachricht(Date datum, String nachricht, String uid) {
		logger.debug("entering speicherNachricht");
		boolean result = false ;
		String query = "INSERT INTO nachricht(nachrichttext,userid,datum) VALUES(?,?,?)";
		try {
			Connection conn = openConnection() ;
			PreparedStatement pstmt = conn.prepareStatement(query) ;
			pstmt.setString(1, nachricht) ;
			pstmt.setString(2, uid) ;
			pstmt.setDate(3, datum) ;
			pstmt.execute() ;
			pstmt.close();
			conn.close(); 
			result = true ;
		} catch (SQLException sqle) {
			logger.error("SQLException occured (Query=" + query + ")", sqle) ;
			result = false ;
		}
		return result;
	}
	

}
